// pages/tool/card/make/making/design/design/design.js
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        current: 1,
        data: [],
        designerWidth: 0,
        designerHeight1: 0,
        designerHeight2: 0,
        showbox: true,
        toupload: {},
        addpro: '',
        areas1: [],
        areas2: [],
        wizarda: true,
        wizardb: true,
        wizardindexa: 0,
        wizardindexb: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        this.setData({
            data: {
                "service_time": "( 工作时间9:00-16:00 国定节假日休息 )",
                "exchange": "1.本券4款商品中任意选择一款您喜欢的礼品进行兑换\n2.刮开礼品券上方银色覆盖区域密码，需完成刮开\n3.本券由上海点礼网络科技有限公司发行",
                "exchange1": "1.如因产品断货换季，请耐心等待或改换其他商品\n2.部分商品若因厂家或不可抗力造成缺货，我们将以其他等价值商品予以调换\n3.因填写姓名、地址、联系方式等收货信息不准确而造成的损失，我司概不负责\n4.本券售出不退换、不记名、不挂失、不找零、不兑换现金\n5.购券时已开具发票，发货时不在提供",
            }
        }, () => {
            wx.getSystemInfo({
                success(res) {
                    var width = res.windowWidth - 20;
                    that.setData({
                        designerWidth: width
                    });
                    app.func.getPromise('/v2/test/card/1/' + width)
                        .then(([code, res]) => {
                            that.processTemplate(res.data, 1);
                        });
                    app.func.getPromise('/v2/test/card/2/' + width)
                        .then(([code, res]) => {
                            that.processTemplate(res.data, 2);
                        });
                }
            });
            app.func.getPromise('/v2/westore/seal/my')
                .then(([code, res]) => {
                    if (code == 200) {
                        return res.data;
                    } else {
                        return app.func.reject();
                    }
                })
                .then((url) => {
                    return app.func.promise((resolve, reject) => {
                        wx.downloadFile({
                            url: url,
                            success(res) {
                                resolve(res.tempFilePath);
                            },
                            fail(res) {
                            	reject();
							},
                        })
                    });
                })
                .then((tempFilePath) => {
                    return app.func.promise((resolve, reject) => {
                        wx.getImageInfo({
                            src: tempFilePath,
                            success(res) {
                                resolve(tempFilePath);
                            },
                            fail(res) {
                            	reject();
							}
                        })
                    });
                })
                .then((tempFilePath) => {
                    that.setData({
                        ["data.companyimg"]: tempFilePath,
                        ["toupload.companyimg"]: true
                    })
                }, () => {
                    // that.setData({
                    // 	["data.companyimg"]: "https://files.dianlinet.com/dianli/images/2019-11-09/18-03-23.jpg"
                    // })
                });
        });
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function (res) {
        let result = app.func.getModalResult();
        if(result != null) {
            this.setData({
                addpro: result
            }, () => {
                this.setData({
                    addpro: []
                });
            });
        }
    },

    processTemplate(template, index) {
        let areas = JSON.parse(template);
        let height = 0;
        var that = this;
        for (let i = 0; i < areas.length; i++) {
            let area = areas[i];
            area.top = height;
            height = height + area.height;
        }
        var areaname = "areas" + index;
        var desingerHeight = "designerHeight" + index;
        that.setData({
            [areaname]: areas,
            [desingerHeight]: height
        });
    },

    selfmake: function (e) {
        wx.navigateTo({
            url: '/tools/pages/tool/card/make/making/selfmake/selfmake'
        })
    },

    //选择A面  B面
    choosetype: function (e) {
        var index = e.currentTarget.dataset.index;
        this.setData({current: index});
    },

    wizardFinishA: function(e) {
        this.setData({wizarda:false}, () => {
            if(this.data.wizardb) {
                this.setData({current: 2});
            }
        });
    },

    wizardFinishB: function(e) {
        this.setData({wizardb:false}, () => {
            if(this.data.wizarda) {
                this.setData({current: 1});
            } else {
                console.log("wizard finish");
            }
        });
    },

    wizardNextA: function(e) {
        this.setData({
            wizardindexa: e.detail.index
        });
    },

    wizardNextB: function(e) {
        this.setData({
            wizardindexb: e.detail.index
        });
    },

    selfstyle: function () {
        this.setData({
            showbox: true
        });
    },

    addproduct: function () {
        var length = Object.keys(this.data.data).length - 5;
        wx.navigateTo({
            url: "/tools/pages/tool/card/make/addproduck/addproduct?id=null&length=" + length
        })
    },

    onDataChangeda: function (res) {
        console.log(res);
        var toupdate = 'data.' + res.detail.field;
        var that = this;
        var toset = [];
        if(res.detail.wizard != null) {
            toset["wizardindexa"] = res.detail.wizard;
        }
        if (res.detail.data != null) {
            toset[toupdate] = res.detail.data ? res.detail.data : null;
            this.setData(toset, () => {
                if (res.detail.toupload != null) {
                    var toupload = "toupload." + res.detail.toupload;
                    that.setData({
                        [toupload]: true,
                    })
                }
            });
        } else {
            var data = this.data.data;
            delete data[res.detail.field];
            that.setData({"data": data});
        }
    },

    onDataChangedb: function (res) {
        console.log(res);
        var toupdate = 'data.' + res.detail.field;
        var that = this;
        var toset = [];
        if(res.detail.wizard != null) {
            toset["wizardindexb"] = res.detail.wizard;
        }
        if (res.detail.data != null) {
            toset[toupdate] = res.detail.data ? res.detail.data : null;
            this.setData(toset, () => {
                if (res.detail.toupload != null) {
                    var toupload = "toupload." + res.detail.toupload;
                    that.setData({
                        [toupload]: true,
                    })
                }
            });
        } else {
            var data = this.data.data;
            delete data[res.detail.field];
            that.setData({"data": data});
        }
    },

    upload: function () {
        let toupload = this.data.toupload;
        let data = this.data.data;
        var promises = [];
        var i = 0;
        for (let key in toupload) {
            let suffix = i++;
            let value = toupload[key];
            if (value) {
                let src = data[key];
                promises.push(
                    app.func.uploadPromise("/v2/image/upload", src, 'file', {suffix:suffix}).then(function ([code, res]) {
                        if (code == 3102 || code == 3103) {
                            return app.func.toastPromise('图片内容违规').then((resolve, reject) => {
                                reject();
                            });
                        } else {
                            data[key] = res.data;
                            toupload[key] = false;
                        }
                    })
                );
            }
        }
        return app.func.promise_all(promises).then(() => {
            return app.func.promise((resolve, reject) => {
                this.setData({
                    data: data,
                    toupload: toupload
                }, resolve);
            });
        })
    },

    preview: function (res) {
        console.log(JSON.stringify(this.data.data));
        this.upload()
            .then(() => {
                var data = this.data.data;
                var urls = [];
                app.func.postPromise("/v2/test/card/preview/1", data)
                    .then(([code, res]) => {
                        urls.push(res.data);
                        return app.func.postPromise("/v2/test/card/preview/2", data);
                    })
                    .then(([code, res]) => {
                        urls.push(res.data);
                    })
                    .then(() => {
                        wx.previewImage({
                            current: urls[0],
                            urls: urls
                        })
                    })
            });
    },

    //提交信息
    submit_info: function () {
        var data = this.data.data;
        if (data.title.length == 0) {
            app.func.toastPromise('面值不能为空');
            return;
        } else if (data.time.length == 0) {
            app.func.toastPromise('卡券有效期不能为空');
            return;
        } else if (!data.product1) {
            app.func.toastPromise('产品不能为空');
            return;
        }

        this.upload()
            .then(() => {
                // var atemplate = JSON.stringify(this.data.areas1);
                // var btemplate = JSON.stringify(this.data.areas2);
                var params = JSON.stringify(this.data.data);
                app.func.postPromise('/card/template', {
                    a_template: '',
                    b_template: '',
                    params: params,
                }).then(([code, res]) => {
                    if (code == 200) {
                        app.func.toastPromise('提交成功')
                            .then(() => {
                                wx.redirectTo({
                                    url: '/tools/pages/tool/card/make/making/design/submit/submit?id=' + res.data.id + '&title=' + res.data.title,
                                })
                            })
                    } else {
                        app.func.toastPromise(res.message);
                    }
                })
            });
    }
})
